package com.milestone.fitnesspersonaltrainer.network;

import android.content.Context;
import android.os.Environment;

import com.milestone.fitnesspersonaltrainer.constants.ConstantCode;
import com.milestone.fitnesspersonaltrainer.network.encrypt.JsonConverterFactory;

import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Created by shendawei on 17/2/8.
 */
@EBean(scope = EBean.Scope.Singleton)
public class RetrofitBuilder {

    @RootContext
    Context context;
    private static final long TIMEOUT_CONNECT = 30 * 1000;
    private static Retrofit mRetrofit;

    public Retrofit build() {
        if (mRetrofit == null) {
            File cacheDirectory = new File(Environment.getExternalStorageDirectory(), "/wallpaper/cache");
            long maxSize = 1024 * 1024 * 1024 ;
            Cache cache = new Cache(cacheDirectory, maxSize);

            OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
                    .connectTimeout(TIMEOUT_CONNECT, TimeUnit.MILLISECONDS)
                    .cache(cache)
                    .retryOnConnectionFailure(true);

            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.addInterceptor(loggingInterceptor);


            mRetrofit = new Retrofit.Builder()
                    .baseUrl(ConstantCode.BASE_PATH)
                    .addConverterFactory(JsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(httpClient.build())
                    .build();
        }

        return mRetrofit;
    }
}
